package com.lmq.backend.consumer;

import com.alibaba.fastjson.JSONObject;
import com.lmq.backend.consumer.utils.Game;
import com.lmq.backend.mapper.BotMapper;
import com.lmq.backend.mapper.RecordMapper;
import com.lmq.backend.mapper.UserMapper;
import com.lmq.backend.pojo.Bot;
import com.lmq.backend.pojo.User;
import com.lmq.backend.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/websocket/{token}")  // 不要以'/'结尾
public class WebSocketServer {

    public static ConcurrentHashMap<Integer, WebSocketServer> users = new ConcurrentHashMap<>();
    private Session session = null;
    private User user;

    public static UserMapper userMapper;
    public static RecordMapper recordMapper;

    private static BotMapper botMapper;

    public static RestTemplate restTemplate;

    private final static String addPlayerUrl = "http://127.0.0.1:8998/player/add/";
    private final static String removePlayerUrl = "http://127.0.0.1:8998/player/remove/";

    public Game game = null;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        WebSocketServer.userMapper = userMapper;
    }

    @Autowired
    public void setRecordMapper(RecordMapper recordMapper) {
        WebSocketServer.recordMapper = recordMapper;
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        WebSocketServer.restTemplate = restTemplate;
    }

    @Autowired
    public void setBotMapper(BotMapper botMapper) {
        WebSocketServer.botMapper = botMapper;
    }
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        this.session = session;
        System.out.println("open");

        Integer userId = -1;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = Integer.parseInt(claims.getSubject());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        user = userMapper.selectById(userId);
        if(user != null) {
            users.put(userId, this);
        }else {
            this.session.close();
        }
        System.out.println(user);
    }

    @OnClose
    public void onClose() {
        System.out.println("close");
        if(this.user != null) {
            stopMatching();
            users.remove(user.getId());
        }
    }

    public static void startGame(Integer userAId, Integer aBotId, Integer userBId, Integer bBotId) {
        User userA = userMapper.selectById(userAId);
        User userB = userMapper.selectById(userBId);

        Bot botA = botMapper.selectById(aBotId);
        Bot botB = botMapper.selectById(bBotId);

        Game game = new Game(13, 14, 20, userA.getId(), botA, userB.getId(), botB);
        game.createMap();
        if (users.get(userA.getId()) != null)
            users.get(userA.getId()).game = game;

        if (users.get(userB.getId()) != null)
            users.get(userB.getId()).game = game;

        game.start();

        JSONObject initMessage = new JSONObject();
        initMessage.put("a_id", game.getPlayerA().getId());
        initMessage.put("a_sx", game.getPlayerA().getSx());
        initMessage.put("a_sy", game.getPlayerA().getSy());
        initMessage.put("b_id", game.getPlayerB().getId());
        initMessage.put("b_sx", game.getPlayerB().getSx());
        initMessage.put("b_sy", game.getPlayerB().getSy());
        initMessage.put("gamemap", game.getG());


        JSONObject respA = new JSONObject();
        respA.put("event", "start-matching");
        respA.put("opponent_username", userB.getUsername());
        respA.put("opponent_photo", userB.getPhoto());
        respA.put("game", initMessage);
        if (users.get(userA.getId()) != null)
            users.get(userA.getId()).sendMessage(respA.toJSONString());

        JSONObject respB = new JSONObject();
        respB.put("event", "start-matching");
        respB.put("opponent_username", userA.getUsername());
        respB.put("opponent_photo", userA.getPhoto());
        respB.put("game", initMessage);
        if (users.get(userB.getId()) != null)
            users.get(userB.getId()).sendMessage(respB.toJSONString());
    }

    private void startMatching(Integer botId) {
        System.out.println("start-matching");
        MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
        data.add("userId", this.user.getId().toString());
        data.add("rating", this.user.getRating().toString());
        data.add("botId", botId.toString());
        restTemplate.postForObject(addPlayerUrl, data, String.class);
    }

    private void stopMatching() {
        System.out.println("stop-matching");
        MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
        data.add("userId", this.user.getId().toString());
        restTemplate.postForObject(removePlayerUrl, data, String.class);
    }

    private void move(Integer direction) {
        if(this.user.getId().equals(this.game.getPlayerA().getId())) {
            if(game.getPlayerA().getBotId().equals(-1)) {
                game.setNextStepA(direction);
            }
        }else if(this.user.getId().equals(this.game.getPlayerB().getId())) {
            if(game.getPlayerB().getBotId().equals(-1)) {
                game.setNextStepB(direction);
            }
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("message");
        JSONObject data = JSONObject.parseObject(message);
        String event = data.getString("event");
        if("start-matching".equals(event)) {
            startMatching(data.getInteger("bot_id"));
        }else if("stop-matching".equals(event)) {
            stopMatching();
        }else if("move".equals(event)) {
            move(data.getInteger("direction"));
        }else {
            System.out.println("Maybe error");
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public void sendMessage(String message) {
        synchronized (this.session) {
            try {
                this.session.getBasicRemote().sendText(message);
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}